package com.freexiaoyu.freevideoplay;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.SurfaceHolder;

import androidx.annotation.OptIn;
import androidx.appcompat.app.AppCompatActivity;



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.media.MediaPlayer;

import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.ByteArrayDataSource;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.upstream.TransferListener;
import com.google.android.exoplayer2.util.Util;

public class VideoFFmpegActivity extends AppCompatActivity {

    private ServerSocket serverSocket;

    PlayerView mPlayerView;

    private ExoPlayer mExoPlayer;
    MediaSource mediaSource;
    private SurfaceHolder surfaceHolder;
    private DataInputStream dataInputStream;
    private MediaPlayer mediaPlayer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_ffmpeg);
        mPlayerView = findViewById(R.id.video_view);
        mExoPlayer = new ExoPlayer.Builder(getBaseContext()).build();
        mPlayerView.setPlayer(mExoPlayer);

        new Thread(() -> {
            try {
                serverSocket = new ServerSocket(22000);
                //startDecoding(serverSocket.accept());
                //playVideoStream(serverSocket.accept().getInputStream());
                //playVideoStream2(serverSocket.accept());

                String videoPath = Environment.getExternalStorageDirectory()+ File.separator + "Download" + File.separator + System.currentTimeMillis()+".mp4";
                TcpVideoStreamSaver.saveFile2(serverSocket.accept().getInputStream(),videoPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

    }


    // 接收InputStream并播放视频（仅适用于小型视频流）
    private void playVideoStream2(Socket clientSocket) {
// 在你的ClientHandler中使用这个工厂来创建MediaSource
        runOnUiThread(() -> {
            MediaSource mediaSource = new ProgressiveMediaSource.Factory(new SocketDataSourceFactory(clientSocket))
                    .createMediaSource(MediaItem.fromUri("udp://192.168.1.11:22001")); // 使用dummy URI，因为数据来自Socket
            mExoPlayer.setMediaSource(mediaSource);
            mExoPlayer.prepare();
            mExoPlayer.play();
        });
    }

    class SocketDataSourceFactory implements DataSource.Factory {
        private final Socket socket;

        public SocketDataSourceFactory(Socket socket) {
            this.socket = socket;
        }


        @Override
        public DataSource createDataSource() {
            try {
                return new ByteArrayDataSource(readFromSocket(socket));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        private byte[] readFromSocket(Socket socket) throws IOException {
            // 将InputStream读取到ByteArrayOutputStream中
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048]; // 使用更大的缓冲区以提高效率
            int bytesRead;
            while ((bytesRead = socket.getInputStream().read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }

            // 将数据转换为字节数组
            byte[] videoData = byteArrayOutputStream.toByteArray();
            return videoData;
        }
    }


    // 接收InputStream并播放视频
    private void playVideoStream(InputStream inputStream) {
        try {
            // 将InputStream读取到ByteArrayOutputStream中
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }

            // 将ByteArrayOutputStream转换为ByteArrayInputStream
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

            // 创建自定义DataSource
            DataSource dataSource = new DataSource() {
                @Override
                public int read(byte[] buffer, int offset, int length) throws IOException {
                    int bytesRead = byteArrayInputStream.read(buffer, 0, length);
                    return bytesRead == -1 ? 0 : bytesRead;
                }

                @Override
                public void addTransferListener(TransferListener transferListener) {

                }

                @Override
                public long open(DataSpec dataSpec) throws IOException {
                    return byteArrayInputStream.available();
                }


                @Override
                public Uri getUri() {
                    return Uri.EMPTY;
                }

                @Override
                public void close() throws IOException {
                    byteArrayInputStream.close();
                }
            };

            // 使用自定义DataSource创建MediaSource
            String userAgent = Util.getUserAgent(this, "YourAppName");
            DataSource.Factory dataSourceFactory = new DataSource.Factory() {
                @Override
                public DataSource createDataSource() {
                    return dataSource;
                }
            };

            MediaSource mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
                    .createMediaSource(MediaItem.fromUri(Uri.EMPTY)); // 使用空URI，因为我们已经有自定义DataSource

            // 设置MediaSource给ExoPlayer
            mExoPlayer.setMediaSource(mediaSource);
            mExoPlayer.prepare();
            mExoPlayer.play();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Util.SDK_INT >= 21) {
            mExoPlayer.release();
        } else {
            mExoPlayer.release();
            mExoPlayer = null;
        }
    }

}